import React from 'react'
import { Icon, Form, TextArea, Button } from 'semantic-ui-react'
import './ChatWindow.css'
import axios from 'axios'
import handle from './tools/wsmain.js'
import IMEvent from './tools/IMEvent.js'
import { Toast } from 'antd-mobile'

export default class ChatWindow extends React.Component {
  constructor() {
    super()

    this.state = {
      listData: [], //聊天记录
      msgContent: '', //要发送的聊天内容
      client: null //WebSocket客户端
    }
  }

  async componentDidMount() {
    const { from_user, to_user } = this.props.currentInfo

    // 获取消息列表
    const res = await axios.post('chats/info', {
      from_user,
      to_user
    })

    this.setState({
      listData: res.data.list
    })

    // 向后台消息服务器注册客户端
    // 打开聊天窗口的时候，需要向服务器注册用户ID
    let currentUser = localStorage.getItem('uid')
    let client = handle(currentUser, data => {
      console.log(data)
      // 该回调函数用来处理服务器返回的消息（其实就是对方发送消息）
      // 其实就是接收对方返回的消息
      // let newList = [...this.state.listData];
      // data.content表示接受到消息内容
      // newList.push(JSON.parse(data.content));
      // this.setState({
      //   listData: newList
      // })
    })

    this.setState({
      client
    })
  }

  // 受控组件的用法
  handleChange = e => {
    this.setState({
      msgContent: e.target.value
    })
  }

  // 发送消息
  sendMsg = () => {
    if (this.state.msgContent.trim().length === 0) {
      Toast.show('请输入内容!', 2)
      return
    }
    // 把用户输入的信息封装称为数据包，然后发送到后台
    const { from_user, to_user, avatar } = this.props.currentInfo
    // 组装数据
    let pdata = {
      id: new Date().getTime(),
      from_user: from_user,
      to_user: to_user,
      avatar: avatar,
      chat_msg: this.state.msgContent
    }
    // 把消息发送出去
    this.state.client.emitEvent(IMEvent.MSG_TEXT_SEND, JSON.stringify(pdata))
    // 把本人发送的消息添加到本地窗口中
    let newArr = [...this.state.listData, pdata]
    this.setState({
      listData: newArr
    })
  }

  render() {
    // 取出父组件传递过来的值
    const { username } = this.props.currentInfo
    const { listData } = this.state

    // 获取当前用户ID（用于判断当前聊天用户）
    let currentUser = parseInt(localStorage.getItem('uid'))

    const lis = listData.map(item => {
      return (
        <li
          key={item.id}
          className={
            currentUser === item.from_user
              ? 'chat-info-left'
              : 'chat-info-right'
          }
        >
          <img src="http://47.96.21.88:8086/public/icon.png" alt="" />
          <span>{item.chat_msg}</span>
        </li>
      )
    })

    return (
      <div className="chat-window">
        {/* 1.0 标题 */}
        <div className="chat-window-title">
          <Icon
            onClick={this.props.hideChatWindow}
            name="angle left"
            className="chat-ret-btn"
            size="large"
          />
          <span>{username}</span>
        </div>
        {/* 2.0 聊天列表 */}
        <div className="chat-window-content">
          <ul>{lis}</ul>
        </div>
        {/* 3.0 聊天窗口 */}
        <div className="chat-window-input">
          <Form>
            <TextArea
              onChange={this.handleChange}
              value={this.state.msgContent}
              placeholder="请输入聊天内容..."
            />
            <Button onClick={this.props.hideChatWindow}>关闭</Button>
            <Button primary onClick={this.sendMsg}>
              发送
            </Button>
          </Form>
        </div>
      </div>
    )
  }
}
